﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;

namespace SNSpirit.Security
{
    public class SecureStringContext : IDisposable
    {
        public SecureStringContext(SecureString secureStr)
        {
            if (secureStr == null)
                throw new ArgumentNullException("secureStr");
            this._bstrPtr = Marshal.SecureStringToBSTR(secureStr);
        }

        public string Content
        {
            get
            {
                return Marshal.PtrToStringBSTR(this._bstrPtr);
            }
        }

        public void Dispose()
        {
            if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) == 0)
            {
                Marshal.ZeroFreeBSTR(this._bstrPtr);
                GC.Collect();
            }
        }

        private int _isDisposed;

        private IntPtr _bstrPtr;
    }
}
